#include <Windows.h>
#include <strsafe.h>
#include <commctrl.h>

class Win32Exception {
public:
	Win32Exception() : error_code_(GetLastError()), error_message_(nullptr) {
		FormatErrorMessage();
		ShowErrorMessage();
	}

	~Win32Exception() {
		if (error_message_) {
			LocalFree(error_message_);
			error_message_ = NULL;
		}
	}
	void FormatErrorMessage() {
		DWORD nMsgLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL, error_code_, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
			(LPTSTR)&error_message_, 0, NULL);
		if (nMsgLen == 0 || !error_message_) {
			error_message_ = TEXT("Unknown error");
		}
	}

	void ShowErrorMessage() const {
		TCHAR buffer[256];
		StringCchPrintf(buffer, 256, TEXT("Code = %u, Mean = %s"), error_code_, (LPTSTR)error_message_);
		MessageBox(NULL, buffer, TEXT("error"), MB_OK);
	}

private:
	DWORD error_code_;
	LPTSTR error_message_;
};


// 使用案例
/*
SetLastError(ERROR_FILE_NOT_FOUND);
Win32Exception();
*/
